package com.servlet;

import java.io.IOException;
import java.util.List;

import javax.jws.WebService;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.data.StudentData;
import com.entity.Student;
import com.service.LoginService;

@WebServlet(urlPatterns = "/servlet/login.do")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String remeberMe = request.getParameter("remeberMe");
		StringBuffer message = new StringBuffer();
		// 获得session对象
		HttpSession session = request.getSession();

		ServletContext application = request.getServletContext();

		if (LoginService.checkLogin(userName, password, message)) {
			session.setAttribute("userName", userName);
			Cookie nameCookie = new Cookie("userName", "");
			Cookie passwordCookie = new Cookie("password", "");
			if ("remeberMe".equals(remeberMe)) {
				nameCookie.setValue(userName);
				passwordCookie.setValue(password);
				nameCookie.setMaxAge(60 * 60 * 24 * 7);
				passwordCookie.setMaxAge(60 * 60 * 24 * 7);
			}
			response.addCookie(nameCookie);
			response.addCookie(passwordCookie);

			List<Student> stdList = StudentData.getInitStdList();
			application.setAttribute("stdList", stdList);

			response.sendRedirect("../index.jsp");
		} else {
			request.setAttribute("message", message.toString());
			// 相对路径
			request.setAttribute("location", "../login.jsp");
			/*
			 * //绝对路径 request.setAttribute("location",
			 * <%=request.getContextPath()%>+"/login.jsp");
			 */
			request.getRequestDispatcher("../error.jsp").forward(request, response);
		}

		/* super.doPost(request, response); */
	}
}
